// 封装 request 基于uni.request
import { apiBaseUrl, openBaseUrl } from './config.js'
import { getToken, message } from './auth.js'

export default {
  config: {
    baseUrl: apiBaseUrl,
    headers: {
      'content-type': 'application/json',
    },
    dataType: 'json',
    responseType: 'text',
  },
  interceptor: {
    request: function (_config) {},
    response: null,
  },
  request(options) {
    return new Promise((resolve, reject) => {
      let _config = null
      options.url = this.config.baseUrl + options.url
      options.header = this.config.headers
      if(!options.url.includes('api/auth/appletLogin')){
        options.header.Authorization = getToken()
      }
      options.complete = response => {
        // console.log('response', response)
        response.config = _config
        if (response.statusCode === 200) {
          const { status, data, msg } = response.data
          if (status === 200 || status == null) {
            resolve(response.data)
          } else if (status === 401 || status === 402) {
            uni.navigateTo({
              url: '/pages/login/index',
            })
          } else {
            reject(response.data)
            // message(msg)
          }
        } else {
          reject(response)
        }
      }

      _config = Object.assign({}, this.config, options)

      if (this.interceptor.request) {
        this.interceptor.request(_config)
      }

      uni.request(_config)
    })
  },
  get(url, data, showtips, options) {
    data = data ? data : {}

    if (!options) {
      options = {}
    }
    options.url = url
    options.data = data
    options.method = 'GET'
    options.showtips = showtips
    return this.request(options)
  },
  post(url, data, showtips, options) {
    if (!options) {
      options = {}
    }
    options.url = url
    options.data = data
    options.method = 'POST'
    options.showtips = showtips
    return this.request(options)
  },
  put(url, data, showtips, options) {
    if (!options) {
      options = {}
    }
    options.url = url
    options.data = data
    options.method = 'PUT'
    options.showtips = showtips
    return this.request(options)
  },
  del(url, data, showtips, options) {
    if (!options) {
      options = {}
    }
    options.url = url
    options.data = data
    options.showtips = showtips
    options.method = 'DELETE'
    return this.request(options)
  },
}
